package com.yycx.module.weixin.provider.config;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Binary Wang
 */
@Configuration
@ConditionalOnClass(WxPayService.class)
@EnableConfigurationProperties(WxPayProperties.class)
@AllArgsConstructor
public class WxPayConfiguration {
    private WxPayProperties properties;

    @Bean("wxPayService2")
    @ConditionalOnMissingBean
    public WxPayService wxPayService2() {
        List<WxPayProperties.WxPayConfig> wxPayConfigs = properties.getWxPayConfigs();
        if (wxPayConfigs == null) {
            throw new RuntimeException("大哥，拜托先看下项目首页的说明（readme文件），添加下支付相关配置，注意别配错了！");
        }
        WxPayService service = new WxPayServiceImpl();
        service.setMultiConfig(wxPayConfigs
                .stream().map(config -> {
                    WxPayConfig payConfig = new WxPayConfig();
                    payConfig.setAppId(StringUtils.trimToNull(config.getAppId()));
                    payConfig.setMchId(StringUtils.trimToNull(config.getMchId()));
                    payConfig.setMchKey(StringUtils.trimToNull(config.getMchKey()));
                    payConfig.setSubAppId(StringUtils.trimToNull(config.getSubAppId()));
                    payConfig.setSubMchId(StringUtils.trimToNull(config.getSubMchId()));
                    payConfig.setKeyPath(StringUtils.trimToNull(config.getKeyPath()));
                    payConfig.setPrivateKeyPath(StringUtils.trimToNull(config.getPrivateKeyPath()));
                    payConfig.setPrivateCertPath(StringUtils.trimToNull(config.getPrivateCertPath()));
                    payConfig.setApiV3Key(StringUtils.trimToNull(config.getApiV3Key()));
                    payConfig.setCertSerialNo(StringUtils.trimToNull(config.getCertSerialNo()));
                    payConfig.setUseSandboxEnv(false); // 可以指定是否使用沙箱环境
                    return payConfig;
                }).collect(Collectors.toMap(WxPayConfig::getAppId, a -> a, (o, n) -> o)));
        return service;
    }

}
